# -*- coding: utf-8 -*-

import cx_Oracle
import psycopg2 as postgres
import json

from DAC.Func import Func
from DAC.Config import Config
from DAC.Config import DbType


class Dac(object):
    """Dbs-数据库操作单元"""
    
    __cfg = Config()

    @classmethod
    def _open_conn(cls, link_name = 'default'):
        link = cls.__cfg.link_map[link_name]
        if link['dbtype'] == DbType.ORACLE:
            conn_str = "%s/%s@%s:%s/%s".format(link['user'], link['pwd'], link['addr'], link['port'], link['db'])
            conn = cx_Oracle.connect(conn_str)
        elif link['dbtype'] == DbType.POSTGRES:
            conn = postgres.connect(database=link['db'], user=link['user'], password=link['pwd'], host=link['addr'],
                                    port=link['port'])
        else:
            raise Exception("错误了")
        return conn

    @classmethod
    def get_query(cls, sql, link_name = 'default'):
        conn = cls._open_conn(link_name)
        cur = conn.cursor()
        try:
            cur.execute(sql)
        
            des = cur.description
            fields = []
            for item in des:
                fields.append(item[0])
            fields_cnt = len(fields)

            rows = cur.fetchall()
            ds = []
            for row in rows:
                data = {}
                for i in range(fields_cnt):
                    fld = fields[i].lower()
                    data[fld] = row[i]
                    ds.append(data)
            
            resp = {"result": "true", "message": "", "datas": ds}
        except Exception as e:
            err = "get_query过程发生错误: %s".format(e)
            resp = {"result": "false", "message": err}
        finally:
            cur.close()
            conn.close()
        s = json.dumps(resp, ensure_ascii=False)
        print(s)
        return Func.encode_json_str(s)

    @classmethod
    def exec_sql(cls, sql, link_name = 'default'):
        conn = cls._open_conn(link_name)
        cur = conn.cursor()
        try:
            cur.execute(sql)
            conn.commit()       
            resp = {"result": "true", "message": ""}
        except Exception as e:
            err = "exec_sql过程发生错误: %s".format(e)
            resp = {"result": "false", "message": err}
            conn.rollback()
        finally:
            cur.close()
            conn.close()
        s = json.dumps(resp, ensure_ascii=False)
        return Func.encode_json_str(s)

    @classmethod
    def exec_sql_array(cls, sql_array, link_name = 'default'):
        conn = cls._open_conn(link_name)
        cur = conn.cursor()
        try:
            for sql in sql_array:
                cur.execute(sql)
            conn.commit()       
            resp = {"result": "true", "message": ""}
        except Exception as e:
            err = "exec_sql_array过程发生错误: %s".format(e)
            resp = {"result": "false", "message": err}
            conn.rollback()
        finally:
            cur.close()
            conn.close()
            
        s = json.dumps(resp, ensure_ascii=False)
        return Func.encode_json_str(s)
